package com.karry.yl.web.system;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.karry.commons.AliMsg;
import com.karry.commons.Constants;
import com.karry.commons.base.SuperController;
import com.karry.commons.util.NumberUtil;
import com.karry.commons.vo.JsonResponse;
import com.karry.yl.domain.baseinfo.Organization;
import com.karry.yl.domain.system.User;
import com.karry.yl.service.baseinfo.OrganizationService;
import com.karry.yl.service.system.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 修改密码的表现层
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/changePassword")
public class ChangePassword extends SuperController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrganizationService organizationService;

    @RequestMapping
    public String changePassword() {
        return "changePassword";
    }

    /**
     * 检测机构是否存在
     *
     * @param orgName
     * @return
     */
    @RequestMapping("/organizationIsNull")
    @ResponseBody
    public JsonResponse checkEnterprise(String orgName) {
        Organization organization = organizationService.selectOne(new EntityWrapper<Organization>().eq("name", orgName).eq("deleted", false));
        if (organization == null) {
            return new JsonResponse(404, "该机构不存在,请核对后从新输入");
        }
        return JsonResponse.success(organization);
    }

    /**
     * 发送短信异步接口
     *
     * @param phone
     * @return
     */
    @RequestMapping("/sendMsg")
    @ResponseBody
    public JsonResponse sendMsg(String phone, String orgName, HttpSession session) {
        JsonResponse rs = JsonResponse.fail("发送失败！");
        if (null == phone || phone.isEmpty()) {
            rs = JsonResponse.fail("请输入手机号码！");
        } else {
            //判断该手机号用户是否属于输入的机构哦
            Organization organization = organizationService.selectOne(new EntityWrapper<Organization>().eq("name", orgName).eq("deleted", false));
            User u = userService.selectOne(new EntityWrapper<User>().eq("phone", phone).eq("deleted", false));
            if (organization == null) {
                return JsonResponse.fail("该机构不存在,请核对后从新输入");
            }
            Long id = organization.getId();
            if (organization != null && u != null) {
                if (!id.equals(u.getOrgId())) {
                    return JsonResponse.fail("您不属于该机构的用户,请核对后从新输入");
                }
            }

            if (null == u) {
                rs = JsonResponse.fail("手机号不存在或被冻结，详情咨询请联系管理员！");
            } else {
                try {
                    int code = NumberUtil.getRandomInt(Constants.PHONE_VCODE_LEN);
                    String rsCode = AliMsg.send(phone, code, AliMsg.TEMPLATE_CODE, AliMsg.SIGN_NAME);
                    System.out.println("验证码：" + code);
                    if ("OK".equals(rsCode)) {
                        rs = JsonResponse.success("发送成功！");
                        session.setAttribute(Constants.JG_CHANGEPASSWORD_PHONE_CODE, code);
                        session.setAttribute(Constants.JG_CHANGEPASSWORD_CODE_DATE, System.currentTimeMillis());
                        session.setAttribute(Constants.JD_CHANGEPASSWORD_PHONE, phone);
                        session.setAttribute(Constants.JD_CHANGEPASSWORD_ORGID, id);
                    } else if ("isv.BUSINESS_LIMIT_CONTROL".equals(rsCode)) {
                        rs = JsonResponse.success("您操作频繁请稍后再试！");
                    }
                } catch (ClientException e) {
                }
            }
        }
        return rs;
    }

    /**
     * 效验输入信息和验证码
     *
     * @param smsCode
     * @param session
     * @return
     */
    @RequestMapping("/change")
    @ResponseBody
    public JsonResponse change(String orgName, String phone, Integer smsCode, HttpSession session) {
        //判断输入信息是否完善
        if (smsCode == null || orgName == null || phone == null|| "".equals(orgName)|| "".equals(phone)) {
            return new JsonResponse(0, "您输入的信息不全,请核对后从新输入");
        }
        //判断机构是否存在
        Organization organization = organizationService.selectOne(new EntityWrapper<Organization>().eq("name", orgName).eq("deleted", false));
        if (organization == null) {
            return new JsonResponse(0, "该机构不存在,请核对后从新输入");
        }
        //判断手机号是否存在
        User u = userService.selectOne(new EntityWrapper<User>().eq("phone", phone).eq("deleted", false));
        if (u == null) {
            return new JsonResponse(0, "手机号不存在或被冻结，详情咨询请联系管理员！");
        }
        //判断该手机号是否是该机构下的
        Long id = organization.getId();
        if (!id.equals(u.getOrgId())) {
            return new  JsonResponse(0,"您不属于该机构的用户,请核对后从新输入");
        }

        Integer code = (Integer) session.getAttribute(Constants.JG_CHANGEPASSWORD_PHONE_CODE);
        Long date = (Long) session.getAttribute(Constants.JG_CHANGEPASSWORD_CODE_DATE);
        if (code != null && smsCode.equals(code) && (System.currentTimeMillis() - date) <= (1000 * 60 * 15)) {
            return new JsonResponse(200, "校验成功");
        }
        return new JsonResponse(0, "验证码不正确或已超时");
    }

    /**
     * 跳转到跟新页面
     *
     * @return
     */
    @RequestMapping("/inputNewPasswordUI")
    public String inputNewPasswordUI() {
        return "inputPassword";
    }

    /**
     * 更新密码
     *
     * @param password
     * @param session
     * @return
     */
    @RequestMapping("/updatePassword")
    public String updatePassword(String password, HttpSession session) {
        String phone = (String) session.getAttribute(Constants.JD_CHANGEPASSWORD_PHONE);
        if (phone != null) {
            User orgUser = userService.selectOne(new EntityWrapper<User>().eq("phone", phone).eq("deleted", false));
            //设置 新密码
            //修改密码
            orgUser.setPassword(DigestUtils.md5Hex(password));
            userService.updateById(orgUser);
            session.removeAttribute(Constants.JG_CHANGEPASSWORD_PHONE_CODE);
            session.removeAttribute(Constants.JG_CHANGEPASSWORD_CODE_DATE);
            session.removeAttribute(Constants.JD_CHANGEPASSWORD_PHONE);
        }
        return "redirect:/login";
    }
}
